package br.com.projeco.biblioteca.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.svenson.converter.TypeConverter;
import org.svenson.util.ExceptionWrapper;

public  class ResourceDateConverter implements TypeConverter {
	
	private String format;
	private String timeFormat;

	public ResourceDateConverter() {
		this(null, null);
	}

	public ResourceDateConverter(String format) {
		this(format, null);
	}

	public ResourceDateConverter(String format, TimeZone timeZone) {
		setFormat(format);
	}

	public void setFormat(String format) {
		if (format == null) {
			format = "yyyy-MM-dd'T'HH:mm:ss";
		}
		this.format = format;
	}

	private SimpleDateFormat createFormat() {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		// sdf.setTimeZone(timeZone);
		return sdf;
	}

	private SimpleDateFormat createTimeFormat() {
		SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
		// sdf.setTimeZone(timeZone);
		return sdf;
	}

	public Object fromJSON(Object in) {
		if (in == null)
			return null;

		if (in instanceof String) {
			SimpleDateFormat sdf = createFormat();
			if (((String) in).length() > format.length()) {
				sdf = createTimeFormat();
			}

			try {
				Date dt = sdf.parse((String) in);
				return dt;
			} catch (ParseException e) {
				throw ExceptionWrapper.wrap(e);
			}
		} else {
			throw new IllegalArgumentException(
					"Parameter must be a String, was a " + in + " ( "
							+ in.getClass() + ")");
		}
	}

	public Object toJSON(Object in) {
		if (in == null)
			return null;

		if (in instanceof Date) {
			SimpleDateFormat sdf = createTimeFormat();
			return sdf.format(in);
		} else {
			throw new IllegalArgumentException(
					"Parameter must be a java.util.Date, was a " + in);
		}
	}

	public void setTimeFormat(String timeFormat) {
		this.timeFormat = timeFormat;
	}

	public String getTimeFormat() {
		return timeFormat;
	}

}
